import axios from 'axios'
import { storage, errorMsg } from '@/utils/utils'
import Router from 'next/router'

const service = axios.create({
  baseURL: 'http://127.0.0.1:7001',
  timeout: 50000,
})

service.interceptors.request.use(
  (config) => {
    let tokens = storage.get('next_blog_tokens')
    if (tokens) (config.headers)['Authorization'] = tokens
    config.headers = {
      ...config.headers,
    }

    return config
  },
  (error) => Promise.reject(error)
)

// Response interceptors
service.interceptors.response.use(
  (response) => {
    const res = response.data
    if (res.success || (response.request.responseType === 'blob' && response.status === 200)) return response
    errorMsg(res.message || '未知错误')
    if (res.code === 401) {
      window.localStorage.removeItem('next_blog_tokens')
      window.localStorage.removeItem('isLogin')
      window.localStorage.removeItem('next_blog_userInfo')
      window.localStorage.removeItem('userName')
      Router.push('/sign')
    }
    return Promise.reject(res || '未知错误')
  }
)

const getCancelToken = () => {
  let { CancelToken } = axios
  let source = CancelToken.source()
  return source
}

export default service

export {
  getCancelToken
}
